﻿using AutoMapper;
using DFGK_WMS.Context;
using DFGK_WMS.IRepository;
using DFGK_WMS.Model.DTO;
using DFGK_WMS.Model.Models;
using Microsoft.EntityFrameworkCore;
using Microsoft.VisualBasic;
using NPOI.XWPF.UserModel;
using Org.BouncyCastle.Asn1.X509;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Security.Cryptography.Xml;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Linq;
using static Microsoft.EntityFrameworkCore.DbLoggerCategory;
using static NPOI.HSSF.Util.HSSFColor;

namespace DFGK_WMS.Repository
{
    /// <summary>
    /// 盘点单管理
    /// </summary>
    public class TStocktakingOrderRepository : BaseRepository<TStocktakingOrder>, ITStocktakingOrderRepository
    {
        public TStocktakingOrderRepository(DFGK_DB context, IMapper mapper) : base(context, mapper)
        {
        }
        /// <summary>
        /// 导出盘点单号
        /// </summary>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public List<TStocktakingOrder> GetStockingExcel()
        {
            try
            {
                #region 弃用
                //var alist = Context.TStocktakingOrders.AsQueryable();//盘点单
                //var blist=Context.TMaterials.AsQueryable();//物料
                //var clist=Context.TAreas.AsQueryable();//库区
                //var dlist=Context.TWarehouses.AsQueryable();//库房
                //var query = from a in alist
                //            join b in blist
                //            on a.MaterialId equals b.Id
                //            join c in clist
                //            on a.AreaId equals c.Id
                //            join d in dlist
                //            on a.WarehouseId equals d.Id
                //            select new TStocktakingOrderDto
                //            {
                //                Name=a.Name,
                //                FName=d.Name,
                //                KName=c.Name,
                //                WName=b.Name,
                //                BillType=a.BillType,
                //                PlanType=a.PlanType,
                //                StocktakeWay= a.StocktakeWay,
                //                BatchNo = a.BatchNo,
                //                CreateUserName = a.CreateUserName,
                //                CreateDate = a.CreateDate
                //            };
                //return query.ToList();
                #endregion
                var slist=Context.TStocktakingOrders.ToList();
                return slist;
            }
            catch (Exception)
            {

                throw;
            }
        }
        /// <summary>
        /// 新增
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        public bool AddStocktakingOrder(TStocktakingOrderDto dto,out string message)
        {
            using (var tran = Context.Database.BeginTransaction())
            {
                message = "";
                try
                {
                    TStocktakingOrder order = new TStocktakingOrder();
                    order = Mapper.Map<TStocktakingOrder>(dto);
                    //库房
                    var wobj = Context.TWarehouses.Find(dto.WarehouseId);
                    if(wobj!=null && wobj.Status==1)
                    {
                        order.WarehouseName = wobj.Name;
                        order.WarehouseCode = wobj.Code;
                    }
                    else
                    {
                        message = "库房不存在或已被禁用！";
                        return false;
                    }
                    ////库区
                    //var aobj = Context.TAreas.Find(dto.AreaId);
                    //if (aobj!=null && aobj.Status==1)
                    //{
                    //    order.AreaName = aobj.Name;
                    //    order.AreaCode = aobj.Code;
                    //}
                    //else
                    //{
                    //    message = "库区不存在或已被禁用！";
                    //    return false;
                    //}
                    var pandian = Context.TStocktakingOrders.FirstOrDefault(x => x.OrderSn==dto.OrderSn);
                    if (pandian!=null)
                    {
                        message = "盘点单号已重复不能添加";
                        return false;
                    }
                    //状态默认为待盘点
                    order.Status = 1;
                    //盘点计划默认为普通抽盘
                    order.PlanType = 10;
                    //订单明细的数量
                    order.FinishedCount = dto.Inventorys.Count;
                    order.CreateDate = DateTime.Now;
                    order.CreateUserId = dto.NowUserId;
                    order.CreateUserName = dto.NowUserRealName;
                    order.Remark = dto.Remark;
                    order.BillType = dto.BillType;
                    Context.TStocktakingOrders.Add(order);
                    Context.SaveChanges();

                    foreach (var item in dto.Inventorys)
                    {
                        TStocktakingOrderDetail m = new TStocktakingOrderDetail();
                        m.OrderId = order.Id;
                        m.OrderSn = order.OrderSn;
                        m.CellId = item.LocationId;
                        m.CellCode = item.LocationName;
                        m.CellDepthIndex = item.LocationDepth;
                        m.PalletBarcode = item.PalletBarcode;
                        m.Status = 1;
                        m.MaterialId = item.MaterialId;
                        m.MaterialName = item.MaterialName;
                        m.MaterialCode = item.MaterialCode;
                        m.CreateDate = DateTime.Now;
                        m.HasSkuDetail = item.HasSkuDetail;
                        m.Qty = item.AvailableQty;
                        m.QualityState = item.QualityState;
                        m.BatchNo = item.BatchNo;//物料批次
                        m.OwnerId = item.OwnerId;
                        m.OwnerName = item.OwnerName;
                        m.ExpireDate = item.ExpireDate;
                        m.ProductDate = item.ProductDate;
                        m.SupplierId = item.SupplierId;
                        m.SupplierName = item.SmallBatchNo;//详细批次
                        m.MaterialTypeId = item.MaterialTypeId;
                        m.MaterialTypeName = item.MaterialTypeName;
                        m.InventoryId = item.Id;
                        m.WarehouseId = item.WarehouseId;
                        m.LocationName = item.LocationName;
                        m.SmallBatchNo = item.SmallBatchNo;
                        Context.TStocktakingOrderDetails.Add(m);
                        Context.SaveChanges();
                    }
                    tran.Commit();
                    return true;
                }
                catch (Exception ex)
                {
                    tran.Rollback();
                    
                    throw ex;
                }
            }
        }

        /// <summary>
        /// 修改
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        public bool UpdateStocktakingOrder(TStocktakingOrderDto dto,out string message)
        {
            using (var tran = Context.Database.BeginTransaction())
            {
                message = "";
                try
                {
                    TStocktakingOrder order = new TStocktakingOrder();
                    order = Mapper.Map<TStocktakingOrder>(dto);
                    //库房
                    var wobj = Context.TWarehouses.Find(dto.WarehouseId);
                    if (wobj != null && wobj.Status==1)
                    {
                        order.WarehouseName = wobj.Name;
                        order.WarehouseCode = wobj.Code;
                    }
                    else
                    {
                        message = "库房不存在或已被禁用！";
                        return false;
                    }
                    ////库区
                    //var aobj = Context.TAreas.Find(dto.AreaId);
                    //if (aobj != null && aobj.Status==1)
                    //{
                    //    order.AreaName = aobj.Name;
                    //    order.AreaCode = aobj.Code;
                    //}
                    //else
                    //{
                    //    message = "库区不存在或已被禁用！";
                    //    return false;
                    //}
                    //状态默认为待盘点
                    order.Status = 1;
                    //盘点计划默认为普通抽盘
                    order.PlanType = 10;
                    //订单明细的数量
                    order.CreateDate = dto.CreateDate;
                    order.CreateUserId = dto.CreateUserId;
                    order.CreateUserName = dto.CreateUserName;
                    order.FinishedCount = dto.Inventorys.Count;
                    order.ModifyDate = DateTime.Now;
                    order.ModifyUserId = dto.NowUserId;
                    order.ModifyUserName = dto.NowUserRealName;
                    order.BillType = dto.BillType;
                    order.Remark = dto.Remark;
                    Context.TStocktakingOrders.Update(order);
                    Context.SaveChanges();

                    var slist = Context.TStocktakingOrderDetails.Where(x => x.OrderId == order.Id && x.OrderSn == order.OrderSn);
                    if(slist!=null || slist.Any())
                    {
                        Context.TStocktakingOrderDetails.RemoveRange(slist);
                        Context.SaveChanges();
                    }
                    foreach (var item in dto.Inventorys)
                    {
                        TStocktakingOrderDetail m = new TStocktakingOrderDetail();
                        m.OrderId = order.Id;
                        m.OrderSn = order.OrderSn;
                        m.CellId = item.LocationId;
                        m.CellCode = item.LocationCode;
                        m.LocationName = item.LocationName;
                        m.CellDepthIndex = item.LocationDepth;
                        m.PalletBarcode = item.PalletBarcode;
                        m.Status = (int)item.Status;
                        m.MaterialId = item.MaterialId;
                        m.MaterialName = item.MaterialName;
                        m.MaterialCode = item.MaterialCode;
                        m.CreateDate = DateTime.Now;
                        m.HasSkuDetail = item.HasSkuDetail;
                        m.Qty = item.AvailableQty;
                        m.QualityState = item.QualityState;
                        m.BatchNo = item.BatchNo;
                        m.SmallBatchNo = item.SmallBatchNo;
                        m.OwnerId = item.OwnerId;
                        m.OwnerName = item.OwnerName;
                        m.ExpireDate = item.ExpireDate;
                        m.ProductDate = item.ProductDate;
                        m.SupplierId = item.SupplierId;
                        m.SupplierName = item.SupplierName;
                        m.MaterialTypeId = item.MaterialTypeId;
                        m.MaterialTypeName = item.MaterialTypeName;
                        m.InventoryId = item.Id;
                        m.WarehouseId = item.WarehouseId;
                        Context.TStocktakingOrderDetails.Add(m);
                        Context.SaveChanges();
                    }
                    tran.Commit();
                    return true;
                }
                catch (Exception ex)
                {
                    tran.Rollback();
                    throw ex;
                }
            }
        }

        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="ids"></param>
        /// <returns></returns>
        public bool DelStocktakingOrder(int ids)
        {
            try
            {
                //盘点单
                var del = Context.TStocktakingOrders.Find(ids);
                Context.TStocktakingOrders.Remove(del);
                //盘点单明细
                var slis = Context.TStocktakingOrderDetails.Where(x => x.OrderId == ids);
                if(slis.Any())
                {
                    Context.TStocktakingOrderDetails.RemoveRange(slis);
                }
                return Context.SaveChanges() > 0;
            }
            catch (Exception ex)
            {

                throw ex;
            }
        }

        public IEnumerable<object> GetTstockordechaxun(DateTime? startTime, DateTime? endTime, int? wid, int? aid, string? name, int pageIndex, int pageSize, out int totalCount)
        {
            var alist = Context.TStocktakingOrders.AsQueryable();//盘点单
            var blist = Context.TStocktakingOrderDetails.AsQueryable();//盘点订单id
            var clist = Context.TAreas.AsQueryable();//库区
            var dlist = Context.TWarehouses.AsQueryable();//库房

            var query = from a in alist
                        //where a.Status == 1
                        orderby a.CreateDate descending
                        select new
                        {
                            a.Id,//盘点单编号
                            a.WarehouseId,//库房编号
                            a.WarehouseName,//库房名称
                            a.AreaId,//库区id
                            a.AreaCode,//库区编码
                            a.AreaName,//库区名称
                            a.FinishedCount,//数量
                            a.OrderSn,//盘点单号
                            a.Status,
                            a.CreateDate,
                            Inventory = blist.Where(x => x.OrderSn == a.OrderSn && x.Status == a.Status).Select(n => new {
                                Id = n.InventoryId,
                                OrderId = n.Id,
                                n.OrderSn,//盘点订单单号
                                LocationName = n.CellCode,//仓位编码
                                n.PalletBarcode,
                                n.BatchNo,//批次
                                SmallBatchNo = n.SmallBatchNo,//详细批次
                                n.Qty,//库存数量
                                Pty = n.Qty,//盘点数量
                                n.MaterialId,
                                n.MaterialCode,//物料号//蒙牛物料代码
                                n.MaterialName,//物料名称蒙牛物料描述
                                n.Status,//待盘点
                                n.CreateDate,//盘点计划时间
                                n.WarehouseId,
                                n.InventoryId,
                                n.OwnerId,
                                n.OwnerName,
                                shuliang = blist.Where(x => x.OrderId == a.Id).Count()
                            }).ToList(),


                        };
            if (!string.IsNullOrEmpty(name))
            {
                query = query.Where(x => x.OrderSn.Contains(name));
            }
            if (wid != null)
            {
                query = query.Where(x => x.WarehouseId == wid);
            }
            if (aid != null)
            {
                query = query.Where(x => x.AreaId == aid);
            }
            if (startTime != null && endTime != null)
            {
                query = query.Where(s => s.CreateDate.Date >= startTime && s.CreateDate.Date <= endTime);
            }

            query = query.Skip((pageIndex - 1) * pageSize).Take(pageSize);
            totalCount = query.Count();
            //pagesize =query.Select(x=>x.id).Max();
            return query.ToList();
        }

        /// <summary>
        /// 条件查询
        /// </summary>
        /// <param name="ids"></param>
        /// <returns></returns>
        public TStocktakingOrderDto GetStocktakingOrder(int ids)
        {
            var tsobj = Context.TStocktakingOrders.Find(ids);
            TStocktakingOrderDto m = new TStocktakingOrderDto();
            if (tsobj!=null)
            {
                
                m = Mapper.Map<TStocktakingOrderDto>(tsobj);

                var tsoobj = Context.TStocktakingOrderDetails.Where(x => x.OrderId == tsobj.Id);
                if(tsoobj.Any())
                {
                    List<TInventory> inventories = new List<TInventory>();
                    foreach (var item in tsoobj)
                    {
                        TInventory inventory = new TInventory();
                        inventory = Mapper.Map<TInventory>(item);
                        inventory.AvailableQty=item.Qty;
                        inventory.LocationId = item.CellId;
                        inventory.LocationCode = item.CellCode;
                        inventory.LocationDepth = (int)item.CellDepthIndex;
                        inventory.Id = (int)item.InventoryId;
                        inventories.Add(inventory);
                    }
                    //弃用
                    //var ilist = tsoobj.Select(x => new TInventory
                    //{  
                       
                    //    PalletBarcode = x.PalletBarcode,
                    //    Status = x.Status,
                    //    MaterialId = x.MaterialId,
                    //    MaterialName = x.MaterialName,
                    //    MaterialCode = x.MaterialCode,
                    //    CreateDate = x.CreateDate,
                    //    HasSkuDetail = (bool)x.HasSkuDetail,
                    //    AvailableQty = x.Qty,
                    //    QualityState = x.QualityState,
                    //    BatchNo = x.BatchNo,
                    //    OwnerId = x.OwnerId,
                    //    OwnerName = x.OwnerName,
                    //    ExpireDate = x.ExpireDate,
                    //    ProductDate = x.ProductDate,
                    //    SupplierId= x.SupplierId,
                    //    SupplierName = x.SupplierName,
                    //    MaterialTypeId = x.MaterialTypeId,
                    //    MaterialTypeName = x.MaterialTypeName,
                    //    Id = (int)x.InventoryId,
                    //    WarehouseId= x.WarehouseId,
                    //});
                    m.Inventorys = inventories;
                }
            }
            return m;
            
        }

        /// <summary>
        /// 修改状态
        /// </summary>
        /// <param name="m"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public bool UpdTStocktakingOrderState(ReceivingOrderDetailDto m,out string message)
        {
            var robj = Context.TStocktakingOrders.Find(m.Id);

            if (robj != null)
            {            
                switch (robj.Status)
                {
                    case 0:
                        var uobj = Context.TUsers.FirstOrDefault(x => x.Id == m.NowUserId && x.JobNo == m.JobNo);
                        if (uobj != null)
                        {
                            robj.SubmitUserId = m.NowUserId;
                            robj.SubmitUserName = m.NowUserRealName;
                            robj.SubmitDate = DateTime.Now;
                            robj.Remark = m.Remark;
                            //修改为：审核通过
                            robj.Status = 2;
                            Context.TStocktakingOrders.Update(robj);
                            break;
                        }
                        message = "工号有误！";
                        return false;

                    case 1:
                        break;

                    case 2:                
                        robj.ModifyUserId = m.NowUserId;
                        robj.ModifyUserName = m.NowUserRealName;
                        robj.ModifyDate = DateTime.Now;
                        //修改为：作业中
                        robj.Status = 3;
                        Context.TStocktakingOrders.Update(robj);
                        break;

                    case 3:
                        robj.ModifyUserId = m.NowUserId;
                        robj.ModifyUserName = m.NowUserRealName;
                        robj.ModifyDate = DateTime.Now;
                        //修改为：已完成
                        robj.Status = 4;
                        Context.TStocktakingOrders.Update(robj);
                        break;

                    default:
                        break;
                }
                message = "修改成功！";
                return Context.SaveChanges() > 0;
            }
            message = "修改失败！";
            return false;
        }
        public static int Suiji(int min, int max)
        {
            Random random = new Random();
            return random.Next(min, max);
        }
        /// <summary>
        /// 盘点列表显示根据库存查询库区库房
        /// </summary>
        /// <param name="wid"></param>
        /// <param name="aid"></param>
        /// <param name="name"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public List<TInventory> GetWhArList(int? wid, int? aid,string? name, string? cangweibianma, int pageIndex, int pageSize, out int totalCount)
        {
            var ilist = Context.TInventory.AsQueryable().Where(x=>x.WarehouseId==wid);//库存
            //var kucuno = Context.TInventory.AsQueryable();//库存
            var kufango = Context.TWarehouses.AsQueryable();//库房
            var wuliao = Context.TMaterials.AsQueryable();//物料
            var linq = from a in ilist
                       join b in kufango
                       on a.WarehouseId equals b.Id
                       join d in wuliao
                       on a.MaterialId equals
                       d.Id
                       orderby a.LocationName ascending
                       select new
                       {
                           Id = a.Id,
                           //AreaId = c.Id,//库区id
                           BuiltArea = b.BuiltArea,//库房面积
                           WarehouseId = b.Id,//库房id
                           WarehouseName = b.Code,//库房名称
                           BatchNo = a.BatchNo,//批次号
                           DeptName = a.DeptName,//部门名称
                           MaterialCode = a.MaterialCode,//物资编码
                           MaterialName = a.MaterialName,//物资名称
                           MaterialId = a.MaterialId,//物料id
                           LocationCode = a.LocationCode,//仓位编码
                           LocationName = a.LocationName,//货位名称
                           QualityState = a.QualityState,//质量状态
                           PalletBarcode = a.PalletBarcode,//垛条码
                           CreateDate = a.CreateDate,//入库时间
                           AvailableQty = a.AvailableQty,//库区数量
                           SmallBatchNo = a.SmallBatchNo,//小批次号
                           OwnerId = a.OwnerId,//货主id
                           OwnerName = a.OwnerName,//货主
                           Status = a.Status,
                       };

            if (!string.IsNullOrEmpty(name))
            {
                linq = linq.Where(x => x.MaterialName.Contains(name));
            }
            if (!string.IsNullOrEmpty(cangweibianma))
            {
                var cangweiArray = cangweibianma.Split(',');
                linq = linq.Where(x => cangweiArray.Any(b => x.LocationName.Substring(0, 2) == b));
            }
            linq = linq.Skip((pageIndex - 1) * pageSize).Take(pageSize);
            
            var inventories = linq.Select(item => new TInventory
            {
                // 将匿名类型的属性逐一赋值给 TInventory 对象的属性
                Id = item.Id,
                // AreaId = item.AreaId,//库区id
                // BuiltArea = item.BuiltArea,//库房面积
                WarehouseId = item.WarehouseId,//库房id
                WarehouseName = item.WarehouseName,//库房名称
                BatchNo = item.BatchNo,//批次号
                DeptName = item.DeptName,//部门名称
                MaterialCode = item.MaterialCode,//物资编码
                MaterialName = item.MaterialName,//物资名称
                MaterialId = item.MaterialId,//物料id
                LocationCode = item.LocationCode,//仓位编码
                LocationName = item.LocationName,//货位名称
                QualityState = item.QualityState,//质量状态
                PalletBarcode = item.PalletBarcode,//垛条码
                CreateDate = item.CreateDate,//入库时间
                AvailableQty = item.AvailableQty,//库区数量
                SmallBatchNo = item.SmallBatchNo,//小批次号
                OwnerId = item.OwnerId,//货主id
                OwnerName = item.OwnerName,//货主
                Status = item.Status,
                // 其他属性同理
            }).ToList();
            totalCount = inventories.Count();
            return inventories.ToList();
        }

        public List<TStocktakingOrder> GetPDApandianlist(long? planId, string? Ordernum, int pageindex, int pagesize, out int totalcount)
        {
            var list = Context.TStocktakingOrders.AsNoTracking().AsQueryable().OrderByDescending(x => x.CreateDate).Skip((pageindex - 1) * pagesize).Take(pagesize);
            totalcount = list.Count();
            if (!string.IsNullOrEmpty(Ordernum))
            {
                list = list.Where(n => n.OrderSn == Ordernum);
            }
            return list.ToList();
        }

        public object GetPDAlistyi(out int totcalt,int pageindex, int pagesize)
        {
            //int dd = 3;
            //int c = 5;
            //string uname = HttpContext.User.FindFirstValue("UserName");
            //string runame = HttpContext.User.FindFirstValue("RealName");
            //int uid = Convert.ToInt32(HttpContext.User.FindFirstValue("Id"));
            var alist = Context.TStocktakingOrders.AsQueryable();//盘点单
            var blist = Context.TStocktakingOrderDetails.AsQueryable();//盘点订单id
            var clist = Context.TAreas.AsQueryable();//库区
            var dlist = Context.TWarehouses.AsQueryable();//库房

            var query = from a in alist
                        orderby a.CreateDate descending
                        select new
                        {
                            Ordersn=a.OrderSn,//盘点单号
                            items = blist.Where(x=>x.OrderId==a.Id).Select(n => new {
                                pandiandingdan=n.OrderSn,//盘点订单单号
                                Cellcode = n.CellCode,//仓位编码
                                PalletBarcode = n.PalletBarcode,
                                Batchno=n.BatchNo,//批次
                                SupplierName=n.SupplierName,//详细批次
                                Qty = n.Qty,//库存数量
                                Pty = n.Qty,//盘点数量
                                mamecode =n.MaterialCode,//物料号//蒙牛物料代码
                                matername=n.MaterialName,//物料名称蒙牛物料描述
                                qualityStatus = n.Status,//待盘点
                                CreateDate = n.CreateDate,//盘点计划时间
                                WarehouseId = a.WarehouseId,//库房编号
                                WarehouseName = a.WarehouseName,//库房名称
                                AreaId = a.AreaId,//库区id
                                AreaCode = a.AreaCode,//库区编码
                                AreaName = a.AreaName,//库区名称
                                shuliang =blist.Where(x=>x.OrderId==a.Id).Count()

                            }).ToList(),
                            id = a.Id,//盘点单编号
                            WarehouseId = a.WarehouseId,//库房编号
                            WarehouseName = a.WarehouseName,//库房名称
                            AreaId = a.AreaId,//库区id
                            AreaCode = a.AreaCode,//库区编码
                            AreaName = a.AreaName,//库区名称
                            FinishedCount = a.FinishedCount,//数量

                        };
            //pagesize =query.Select(x=>x.id).Max();
            query = query.Skip((pageindex - 1) * pagesize).Take(pagesize);
            totcalt = blist.Count();
            return query.ToList();
        }

        public IEnumerable<object> GetTstockordernums(string? ordersn)
        {
            var danhao = Context.TStocktakingOrders.AsQueryable();
            var pandianmingxi = Context.TStocktakingOrderDetails.AsQueryable();
            var kucun = Context.TInventories.AsQueryable();
            var zong = from a in danhao
                       where a.OrderSn == ordersn
                       orderby a.CreateDate descending
                       select new
                       {
                           /* Id=a.Id,
                            Ordersn=a.OrderSn,//盘点单号
                            CreateTime=a.CreateDate,
                            Cellcode=a.CellCode,
                            Whaid=a.WarehouseId,

                            PalletBarcode = a.PalletBarcode,
                            MaterialName = a.MaterialName,//物料描述
                            MaterialCode = a.MaterialCode,//物料代码
                            Qty=a.Qty,//库存数量
                            OwnerId = a.OwnerId,//货主id
                            OwnerName = a.OwnerName,//货主
                            Bathcno=a.BatchNo,//物料代码
                            detailedbatch = a.SupplierName,*/
                           a.Id,
                           a.OrderSn,

                           a.WarehouseId,
                           a.WarehouseName,
                           a.WarehouseCode,
                           a.AreaId,
                           a.AreaName,
                           a.CreateDate,
                           a.BillType,
                           a.Remark,
                           Inventorys = pandianmingxi.Where(x => x.OrderSn == a.OrderSn).Select(n => new {
                               Id = n.InventoryId,
                               // stockid=n.Id,
                               // n.Id,
                               n.OrderId,
                               n.OrderSn,//盘点订单单号
                               LocationName = n.CellCode,//仓位编码
                               n.PalletBarcode,
                               n.BatchNo,//批次
                               SmallBatchNo = n.SmallBatchNo,//详细批次
                               AvailableQty = n.Qty,//库存数量
                               Pty = n.Qty,//盘点数量
                               n.MaterialId,
                               n.MaterialCode,//物料号//蒙牛物料代码
                               n.MaterialName,//物料名称蒙牛物料描述
                               n.Status,//待盘点
                               n.CreateDate,//盘点计划时间
                               n.WarehouseId,
                               n.OwnerId,
                               n.OwnerName,
                           }).ToList(),


                       };
            //TStocktakingOrderDtos c = new TStocktakingOrderDtos();
            // pageke = zong.Select(x => x.Id).First();
            //   zong = zong.Skip((pageindex - 1) * pageke).Take(pageke);
            //totalt = zong.Count();
            return zong.ToList();

        }
        /// <summary>
        /// 修改盘点状态，及盘点列表状态
        /// </summary>
        /// <param name="ordernum"></param>
        /// <param name="message"></param>
        /// <returns></returns>
        public bool UpdateStatetai(string ordernum, out string message)
        {
            var robj = Context.TStocktakingOrders.FirstOrDefault(x=>x.OrderSn== ordernum);

            if (robj != null)
            {
                switch (robj.Status)
                {
                    case 0://待打印

                        var danhao=Context.TStocktakingOrderDetails.FirstOrDefault(x=>x.OrderSn.Equals(ordernum));
                        if (danhao!=null)
                        {
                            robj.Status = 1;//待盘点
                            Context.TStocktakingOrders.Update(robj);
                           
                            danhao.Status = 1;//待盘点
                            Context.TStocktakingOrderDetails.Update(danhao);
                            break;
                        }
                       
                        message = "没有盘点单号！";
                        return false;

                    case 1://待盘点
                        var  order = Context.TStocktakingOrderDetails.Where(x => x.OrderSn.Equals(ordernum)&&x.Status==1);
                        if (order != null)
                        {
                            robj.Status = 2;//已盘点
                            Context.TStocktakingOrders.Update(robj);
                            foreach (var item in order)
                            {
                                item.Status = 2;
                                Context.TStocktakingOrderDetails.Update(item);
                            }

                            break;

                        }
                        message = "没有盘点单号！";
                        return false;

                    case 2://已盘点
                        var orderd = Context.TStocktakingOrderDetails.FirstOrDefault(x=>x.OrderSn.Equals(ordernum));
                        if (orderd != null)
                        {
                            orderd.Status = 2;//已盘点
                            Context.TStocktakingOrders.Update(robj);

                            orderd.Status = 2;//已盘点
                            Context.TStocktakingOrderDetails.Update(orderd);
                            break;
                        }
                        message = "没有盘点单号！";
                        return false;
                    case 3://已打印
                        var ordery = Context.TStocktakingOrderDetails.FirstOrDefault(x => x.OrderSn.Equals(ordernum));
                        if (ordery != null)
                        {
                            ordery.Status = 2;//已盘点
                            Context.TStocktakingOrders.Update(robj);

                            ordery.Status = 2;//已盘点
                            Context.TStocktakingOrderDetails.Update(ordery);
                            break;
                        }
                        message = "没有盘点单号！";
                        return false;
                    default:
                        break;
                }
                message = "修改成功！";
                return Context.SaveChanges() > 0;
            }
            message = "修改失败！";
            return false;
        }
    }
}
